# Add your Python code here. E.g.
# https://python.microbit.org/v/2
from microbit import *

rows = 5

a = [0 for i in range(rows)]
b = [0 for i in range(rows)]
c = [0 for i in range(rows * 2)]
d = [0 for i in range(rows * 2)]

result = []

display.show(Image.SAD)

def Search(i):
    global a, b, c, d, rows, result
    for j in range(0, rows):
        if b[j] == 0 and c[i + j] == 0 and d[i - j + rows] == 0:
            a[i] = j
            b[j] = 1
            c[i + j] = 1
            d[i - j + rows] = 1
            if i == rows - 1:
                result.append(a)
            else:
                Search(i + 1)

            b[j] = 0
            c[i + j] = 0
            d[i - j + rows] = 0

Search(0)
        
r_iter = 0
        
def on_button_pressed():
    global r_iter, result
    display.clear()
    if r_iter >= len(result):
        display.show(Image.HAPPY)
        r_iter = 0
    else:
        for r in range(len(result[r_iter])):
            c = result[r_iter][r]
            display.set_pixel(c, r, 5)
        
        r_iter += 1
    
while True:
    if button_a.was_pressed() or button_b.was_pressed():
        on_button_pressed()

